<?php

namespace app\controller;

use app\BaseController;
use app\help\EyEncryptHelper;
use app\middleware\CheckToken;
use app\model\EySchedule;
use app\validate\EyScheduleValidate;
use think\annotation\route\Group;
use think\annotation\route\Route;
use think\exception\ValidateException;
use think\facade\Request;
use yzh52521\EasyHttp\Http;


#[Group("api/ey")]
class EyController extends BaseController
{
    protected $middleware = [CheckToken::class];

    protected $pk = ['doctor_code', 'schedule_date'];

    #[Route("POST", "queryDocker")]
    public function queryDockerList()
    {
        $query_data = array(
            //"drCode"=>"1127",
            "deptCode" => '3002',
            "hisAreaCody" => "06",
            //"scheduleBegDate" => "2024-11-24",
            //"scheduleEndDate" => "2024-11-26",
            "tradeSource" => "05"
        );
        $date = Request::post("date");
        if ($date && is_array($date)) {
            $scheduleBegDate = $date[0];
            $scheduleEndDate = $date[1];
            $query_data['scheduleBegDate'] = $scheduleBegDate;
            $query_data['scheduleEndDate'] = $scheduleEndDate;
        }
        $url = 'https://pay.czey.com:8443/apiV2/appointReg/getSourceInfo';

        $encrypt_data = EyEncryptHelper::encrypt_query($query_data);

        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'encrypt' => '4',
        ])->asJson()->post($url, [
            'encryptData' => $encrypt_data,
        ]);

        $result_data = $response->json();
        if ($result_data->code == 200) {
            $data = $result_data->data;
            $decrypt_data = EyEncryptHelper::decryption_result($data);
            return json(json_decode($decrypt_data), 200);
        } else if ($result_data->code == 500) {
            return json(["msg" => $result_data->message], 500);
        }

    }

    #[Route("POST", "saveSchedule")]
    public function addSchedule()
    {
        try{
            validate(EyScheduleValidate::class)->check(request()->post());
        }catch (ValidateException $e){
            return json($e->getError(),500);
        }
        $doctorCode = Request::post("doctorCode");
        $scheduleDate = Request::post("scheduleDate");
        trace($doctorCode);
        trace($scheduleDate);
        $result = EySchedule::where('doctor_code', $doctorCode)->where("schedule_date", $scheduleDate)->count();
        if ($result) {
            return json(["msg" => "已经存在预约信息"], 500);
        }else {
            $eySchedule = new EySchedule;
            $eySchedule->doctorCode = $doctorCode;
            $eySchedule->scheduleDate = $scheduleDate;
            $eySchedule->save();
            return json(["msg" => "预约成功"], 200);
        }
    }

}